package com.gjintel.sdk.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 文件下载
 * @author wei
 *
 */
public class FileDownload {
	/**
	 * 文件下载
	 * 
	 * @param fileName
	 * @param saveName
	 * @param request
	 * @param response
	 * @return
	 */
	public static boolean processDownload(String path, String saveName, HttpServletRequest request, HttpServletResponse response) {
		boolean success = true;
		// 获取文件下载所在的路径
		//String path = request.getServletContext().getRealPath("/upload");
		File fileLoad = new File(path); // 下载文件
		long fileLength = fileLoad.length(); // 文件大小
		byte[] buffer = new byte[1024]; // 缓冲字节数组
		try {
			response.reset();
			response.setHeader("Content-disposition", "attachment;filename=\""
					+ new String(saveName.getBytes("gb2312"), "ISO-8859-1")
					+ "\"");
			response.setContentType("application/octet-stream");
			response.setHeader("Content_Length", String.valueOf(fileLength));

			OutputStream os = response.getOutputStream();
			FileInputStream in = new FileInputStream(fileLoad);
			int hasRead = 0;
			while ((hasRead = in.read(buffer)) != -1) {
				os.write(buffer, 0, hasRead);
			}
			os.flush();
			os.close();
			in.close();
		} catch (IOException e) {
			success = false;
			e.printStackTrace();
		}
		return success;
	}
}
